import { _decorator, Component, Node, ScrollBar, ScrollView, UITransform, Label, Button, Color, ProgressBarComponent, RenderTexture, Size, SpriteFrame, view, Sprite, EventTouch, Texture2D, Game } from 'cc';
import { EventMgr } from '../../../Framework/Scripts/Managers/EventMgr';
import { poolManager } from '../../../Framework/Scripts/Managers/poolManager';
import { ResMgr } from '../../../Framework/Scripts/Managers/ResMgr';
import { SoundMgr } from '../../../Framework/Scripts/Managers/SoundMgr';
import { UIComponent, UIMgr } from '../../../Framework/Scripts/Managers/UIMgr';
import myUtil from '../../../Framework/Scripts/Utils/myUtil';
import { constant, GoldType } from '../constant';
import { GameApp } from '../GameApp';
import { UserData } from '../userData/UserData';
const { ccclass, property } = _decorator;

@ccclass('shop_friendly_UICtrl')
export class shop_friendly_UICtrl extends UIComponent {
    private scrollView: ScrollView = null
    private friendlyData: any = {}
    private infoRoot: Node = null

    private nowChoice: string = "altman"//当前选择

    private model: Node = null
    private sp = null
    private renderTex: RenderTexture = null
    private minMapNode: Node = null
    private touch: Node = null

    private moveSpeed: number = 5
    //  private goldKey: string = "gold"
    private levelGold: number = 0

    private buyGold: number = 0

    private coinNum = null
    private oreNum = null
    private upCoin(name: string, data) {
        this.coinNum.string = UserData.Instance.localData["gold"]
        this.oreNum.string = UserData.Instance.localData["ore"]
    }
    showInfo() {
        this.upCoin("", null)
        EventMgr.Instance.Emit(constant.EVENT_NAME.upHomeTop, null)
        const arr: Node[] = GameApp.Instance.shopShow.getChildByName("root").children
        this.model = GameApp.Instance.shopShow.getChildByName("root").getChildByName(this.nowChoice)

        const rx: number = this.model.eulerAngles.x
        // const ry: number = this.model.eulerAngles.y
        const rz: number = this.model.eulerAngles.z
        this.model.setRotationFromEuler(rx, 0, rz)
        arr.forEach(element => {
            if (element.name == this.nowChoice) {
                element.active = true

            } else {
                element.active = false
            }
        });
        const b: Size = view.getVisibleSize()
        this.sp = null;
        this.renderTex = null;
        this.sp = new SpriteFrame();
        this.renderTex = new RenderTexture();
        this.renderTex.reset({
            width: b.width,
            height: b.height,



        });
        GameApp.Instance.shopCamera.targetTexture = this.renderTex;
        this.sp.texture = this.renderTex;
        this.minMapNode.getComponent(UITransform).width = b.width / 3
        this.minMapNode.getComponent(UITransform).height = b.height / 3
        this.minMapNode.getComponent(Sprite).spriteFrame = this.sp;
        //  const key = this.nowChoice


        this.friendlyData = constant.friendlyData//大表一定要更新


        const root: Node = this.infoRoot.getChildByName("bg")

        const item = this.friendlyData[this.nowChoice]
        const gold_type: GoldType = item["goldType"]//当前资源所需要的货币类型


 

        this.levelGold = item["levelGold"]
        this.buyGold = item["gold"]

        const upLevelBtn: Node = root.getChildByName("upLevelBtn")

        const buyBtn: Node = root.getChildByName("buyBtn")


        root.getChildByName("name").getComponent(Label).string = item["name"]

        root.getChildByName("ProgressBar").getChildByName("level").getComponent(Label).string = item["level"] + "/" + item["maxLevel"]
        root.getChildByName("str").getComponent(Label).string = item["str"]

        root.getChildByName("nullLabel").active = false



        if (item["isBuy"]) {
            //已经购买
            buyBtn.active=false
            upLevelBtn.active=true
            root.getChildByName("ProgressBar").getComponent(ProgressBarComponent).progress = item.level / item.maxLevel

 
                switch (gold_type) {
                    case GoldType.gold:
                        upLevelBtn.getChildByName("gold").getComponent(Label).string = "" + this.levelGold
                        upLevelBtn.getChildByName("icon1").active = true
                        upLevelBtn.getChildByName("icon2").active = false
                      
                        break;
    
                    case GoldType.ore:
                        upLevelBtn.getChildByName("gold").getComponent(Label).string = "" + this.levelGold
                        upLevelBtn.getChildByName("icon1").active = false
                        upLevelBtn.getChildByName("icon2").active = true
                        break;
    
                    default:
                        break;
                }
            
  

            if (item["level"] < item["maxLevel"]) {


              

                upLevelBtn.getComponent(Button).interactable = true
                upLevelBtn.off("click")
                upLevelBtn.on("click", () => {

                    if (this.levelGold > UserData.Instance.localData[gold_type]) {
                        if(gold_type==GoldType.gold){
                            GameApp.Instance.show_tip("金币不足")
                           }else{
                            GameApp.Instance.show_tip("宝石不足") 
                           }


                    } else {
                        UserData.Instance.localData["friendlyData"][this.nowChoice]["level"] += 1
                        UserData.Instance.localData[gold_type] -= this.levelGold
                        UserData.Instance.saveLocalData()
                        this.upEffect()
                        this.showInfo()




                    }

               

                })


            } else {
                buyBtn.active=false
                upLevelBtn.active = false
                root.getChildByName("nullLabel").getComponent(Label).string = "已满级"
                root.getChildByName("nullLabel").active = true

                // if (this.levelGold > UserData.Instance.localData[gold_type]) {
                //     this.init()
                // }
            }
        } else {
            //未购买
            buyBtn.active=true
            upLevelBtn.active=false
            root.getChildByName("ProgressBar").getComponent(ProgressBarComponent).progress = 0
      
                switch (gold_type) {
                    case GoldType.gold:
                        buyBtn.getChildByName("gold").getComponent(Label).string = "" + this.buyGold
    
                        buyBtn.getChildByName("icon1").active = true
                        buyBtn.getChildByName("icon2").active = false
    
                        break;
    
                    case GoldType.ore:
                        buyBtn.getChildByName("gold").getComponent(Label).string = "" + this.buyGold
    
                        buyBtn.getChildByName("icon1").active = false
                        buyBtn.getChildByName("icon2").active = true
    
                        break;
    
                    default:
                        break;
                }
              
                root.getChildByName("nullLabel").getComponent(Label).string = "未购买"
                root.getChildByName("nullLabel").active = true
    
    
                buyBtn.off("click")
                buyBtn.on("click", () => {
    
                    if (this.buyGold > UserData.Instance.localData[gold_type]) {
                           if(gold_type==GoldType.gold){
                            GameApp.Instance.show_tip("金币不足")
                           }else{
                            GameApp.Instance.show_tip("宝石不足") 
                           }
                         
    
                  
    
    
                    } else {
    
    
    
                        UserData.Instance.localData["friendlyData"][this.nowChoice]["isBuy"] = true
                        UserData.Instance.localData["friendlyData"][this.nowChoice]["level"] += 1
                        UserData.Instance.localData[gold_type] -= this.buyGold
                        UserData.Instance.saveLocalData()
                        this.upEffect()
                        this.showInfo()
                
    
                    }
    
                 
                })
            }
      

     

        

    }

    private upEffect() {
        SoundMgr.Instance.playSound(ResMgr.Instance.getAsset("Sounds", "recovery"))

        const up: Node = poolManager.instance.getNode(ResMgr.Instance.getAsset("prefab", "effect/levelUp"), this.model)
        up.layer=131072
        up.children.forEach(element => {
            element.layer=131072
        });
        up.setWorldPosition(this.model.getWorldPosition())
        myUtil.playEffect(up, false, true, 1, true)
    }

    upItem() {
        const arr: Node[] = this.scrollView.content.children
        arr.forEach(element => {
            const rootItem: Node = element.getChildByName("bg")
            if (element.name == this.nowChoice) {
                rootItem.getChildByName("choice").active = true
                rootItem.getChildByName("iconBg").setScale(1, 1, 1)
                rootItem.getChildByName("name").getComponent(Label).color = new Color("#FF5200")
            } else {
                rootItem.getChildByName("choice").active = false
                rootItem.getChildByName("iconBg").setScale(0.8, 0.8, 0.8)
                rootItem.getChildByName("name").getComponent(Label).color = new Color("#0D1036")
            }
        });
    }

    init() {

        EventMgr.Instance.Emit(constant.EVENT_NAME.upHomeTop, null)
        this.friendlyData = constant.friendlyData//大表
        this.infoRoot = this.ViewNode("infoRoot")
        //700 200
        let height: number = 0
        let posY: number = 260

        //用遍历删除节点池
        for (let key in this.friendlyData) {
            const item = this.friendlyData[key]
            const n: Node = poolManager.instance.getNode(ResMgr.Instance.getAsset("GUI", "item/friendlyItem"), this.scrollView.content)
            n.name = key


            posY -= 260
            height += 260
            n.setPosition(0, posY, 0)

            this.scrollView.content.getComponent(UITransform).height = height
            const root: Node = n.getChildByName("bg")
            const imageAsset = ResMgr.Instance.getAsset("GUI", "enemyImg/" + key)

            const spriteFrame = new SpriteFrame();
            const texture = new Texture2D();
            texture.image = imageAsset;
            spriteFrame.texture = texture;
            root.getChildByName("iconBg").getComponent(Sprite).spriteFrame = spriteFrame;
            root.getChildByName("name").getComponent(Label).string = item["name"]



            root.off("click")
            root.on("click", () => {

                this.nowChoice = key

                this.upItem()
                this.showInfo()

            })


        }

        this.upItem()
      //  this.showInfo()

    }
    private onTouchStart(touch: EventTouch) {

    }

    private onTouchMove(touch: EventTouch) {
        //   console.log("m2", this.model);

        const rx: number = this.model.eulerAngles.x
        const ry: number = this.model.eulerAngles.y
        const rz: number = this.model.eulerAngles.z




        const x: number = touch.getDeltaX()
        if (x > 0) {


            this.model.setRotationFromEuler(rx, ry + this.moveSpeed, rz)


        } else {

            this.model.setRotationFromEuler(rx, ry - this.moveSpeed, rz)
        }

    }
    private onTouchEnd(touch: EventTouch) {


    }

    onLoad() {
        EventMgr.Instance.AddEventListener(constant.EVENT_NAME.upShopFriendlyTop, this.upCoin, this)
        this.touch = this.ViewNode("infoRoot/Mask/touch")
        this.touch.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.touch.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.touch.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.touch.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
        this.minMapNode = this.ViewNode("infoRoot/Mask/minMap")
        this.scrollView = this.ViewNode("ScrollView").getComponent(ScrollView)
        this.coinNum = this.ViewNode("cion/Label").getComponent(Label)
        this.oreNum = this.ViewNode("ore/Label").getComponent(Label)
        this.AddButtonListener("outBtn", this, () => {
            GameApp.Instance.isBack = false
            UIMgr.Instance.DestroyUIView(this.node.name)
        })

        this.init()
        this.showInfo()

    }
    onDestroy() {
        EventMgr.Instance.RemoveEventListener(constant.EVENT_NAME.upShopFriendlyTop, this.upCoin, this)

    }
    start() {

    }

    update(dt: number) {

    }
}


